<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/snowzhao/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/snowzhao/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/snowzhao/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/snowzhao/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/snowzhao/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/snowzhao/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/snowzhao/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="android,">










<meta name="description" content="现在在Android开发中很少用到Base64的BASE64Encoder及BASE64Decoder，今天在h5中需要将图片的base64数据转化为图片保存到相册，项目中居然找不到BASE64Encoder及BASE64Decoder类，一顿百度方法怎么可以引用，最后发现还是将BASE64Encoder及BASE64Decoder类源码引入最方便； 直接下载源码 补充下：Base64的加密解密B">
<meta name="keywords" content="android">
<meta property="og:type" content="article">
<meta property="og:title" content="Android 图片和Base64转化，并保存相册">
<meta property="og:url" content="https://vincent_zyt.gitee.io/snowzhao/2019/12/02/Android-图片和Base64转化，并保存相册/index.html">
<meta property="og:site_name" content="snowzhao博客">
<meta property="og:description" content="现在在Android开发中很少用到Base64的BASE64Encoder及BASE64Decoder，今天在h5中需要将图片的base64数据转化为图片保存到相册，项目中居然找不到BASE64Encoder及BASE64Decoder类，一顿百度方法怎么可以引用，最后发现还是将BASE64Encoder及BASE64Decoder类源码引入最方便； 直接下载源码 补充下：Base64的加密解密B">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-12-02T07:50:13.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Android 图片和Base64转化，并保存相册">
<meta name="twitter:description" content="现在在Android开发中很少用到Base64的BASE64Encoder及BASE64Decoder，今天在h5中需要将图片的base64数据转化为图片保存到相册，项目中居然找不到BASE64Encoder及BASE64Decoder类，一顿百度方法怎么可以引用，最后发现还是将BASE64Encoder及BASE64Decoder类源码引入最方便； 直接下载源码 补充下：Base64的加密解密B">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/snowzhao/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://vincent_zyt.gitee.io/snowzhao/2019/12/02/Android-图片和Base64转化，并保存相册/">





  <title>Android 图片和Base64转化，并保存相册 | snowzhao博客</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/snowzhao/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">snowzhao博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">蜕变</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-首页">
          <a href="/snowzhao/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-归档">
          <a href="/snowzhao/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-标签">
          <a href="/snowzhao/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-分类">
          <a href="/snowzhao/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://vincent_zyt.gitee.io/snowzhao/snowzhao/2019/12/02/Android-图片和Base64转化，并保存相册/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="snowzhao">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/snowzhao/images/photo.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="snowzhao博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Android 图片和Base64转化，并保存相册</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-12-02T15:50:13+08:00">
                2019-12-02
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/snowzhao/categories/android/" itemprop="url" rel="index">
                    <span itemprop="name">android</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  606
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  2
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>现在在Android开发中很少用到Base64的BASE64Encoder及BASE64Decoder，今天在h5中需要将图片的base64数据转化为图片保存到相册，项目中居然找不到BASE64Encoder及BASE64Decoder类，一顿百度方法怎么可以引用，最后发现还是将BASE64Encoder及BASE64Decoder类源码引入最方便；</p>
<p><a href="https://download.csdn.net/download/qq_31796651/11828009" target="_blank" rel="noopener">直接下载源码</a></p>
<p>补充下：Base64的加密解密BASE64Encoder及BASE64Decoder是sun公司的内部方法，并没有在java api中公开过。在Android项项目中可以引用Base64类，却不能使用加密解密方法，下载上面源码放入项目直接可以引用；</p>
<p>1、将图片bitmap转成base64数据</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 图片bitmap转成base64数据</span><br><span class="line"> *</span><br><span class="line"> * @param bitmap</span><br><span class="line"> * @return</span><br><span class="line"> */</span><br><span class="line">public String convertIconToString(Bitmap bitmap) &#123;</span><br><span class="line">    ByteArrayOutputStream baos = new ByteArrayOutputStream();// outputstream</span><br><span class="line">    bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);</span><br><span class="line">    byte[] appicon = baos.toByteArray();// 转为byte数组</span><br><span class="line">    String bitString = Base64.encodeToString(appicon, Base64.DEFAULT);</span><br><span class="line">    return bitString;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>2、将图片base64数据转化为bitmap</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"> /**</span><br><span class="line"> * 将图片base64数据转化为bitmap</span><br><span class="line"> * @param imgBase64</span><br><span class="line"> */</span><br><span class="line">public Bitmap base64ToPicture(String imgBase64) &#123;</span><br><span class="line">    byte[] decode = Base64.decode(imgBase64, Base64.DEFAULT);</span><br><span class="line">    Bitmap bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.length);</span><br><span class="line">    return bitmap;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>3、将图片保存到相册并通知刷新</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 将图片保存到相册并通知刷新</span><br><span class="line"> */</span><br><span class="line">public void savePictureToAlbum(Context mContext, Bitmap bitmap) &#123;</span><br><span class="line">    if (bitmap == null) &#123;</span><br><span class="line">        return;</span><br><span class="line">    &#125;</span><br><span class="line">    // 把文件插入到系统图库</span><br><span class="line">    MediaStore.Images.Media.insertImage(mContext.getContentResolver(),</span><br><span class="line">            bitmap, null, null);</span><br><span class="line">    // 通知图库更新</span><br><span class="line">    mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,</span><br><span class="line">            Uri.parse(&quot;file://&quot; + &quot;/sdcard/namecard/&quot;)));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>4、对图片Base64数据解码并生成图片</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"> /**</span><br><span class="line"> * 对图片Base64解码并生成图片</span><br><span class="line"> *</span><br><span class="line"> * @param imgStr      base64数据</span><br><span class="line"> * @param imgFilePath 图片存放地址</span><br><span class="line"> * @return</span><br><span class="line"> */</span><br><span class="line">public boolean generateImage(String imgStr, String imgFilePath) &#123;</span><br><span class="line">    if (imgStr == null) // 图像数据为空</span><br><span class="line">        return false;</span><br><span class="line">    BASE64Decoder decoder = new BASE64Decoder();</span><br><span class="line">    try &#123;</span><br><span class="line">        // Base64解码</span><br><span class="line">        byte[] bytes = decoder.decodeBuffer(imgStr);</span><br><span class="line">        for (int i = 0; i &lt; bytes.length; ++i) &#123;</span><br><span class="line">            if (bytes[i] &lt; 0) &#123;// 调整异常数据</span><br><span class="line">                bytes[i] += 256;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        // 生成jpeg图片</span><br><span class="line">        OutputStream out = new FileOutputStream(imgFilePath);</span><br><span class="line">        out.write(bytes);</span><br><span class="line">        out.flush();</span><br><span class="line">        out.close();</span><br><span class="line">        return true;</span><br><span class="line">    &#125; catch (Exception e) &#123;</span><br><span class="line">        return false;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>最后注意点：<br>含有“data:image/*;base64”的头的编码，在decode或者转化为bitmap的时候就要去掉，否则是无法还原成功的。<br>如我获取到的图片base64数据就是以data:image/png;base64开头的：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&quot;&quot;</span><br></pre></td></tr></table></figure>

<p>处理方法：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">if (!TextUtils.isEmpty(imgUrl) &amp;&amp; imgUrl.contains(&quot;,&quot;)) &#123;</span><br><span class="line">   //拿到真正的base64数据</span><br><span class="line">    String base64Img = imgUrl.split(&quot;,&quot;)[1];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


      
    </div>
    
    
    

 
<div>
  
    <div>
    
        <div style="text-align:center;color: #666;font-size:16px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>
  
</div>

    

    

    
    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/snowzhao/tags/android/" rel="tag"># android</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/snowzhao/2019/12/02/Android-更好用的图片加载库/" rel="next" title="Android 更好用的图片加载库">
                <i class="fa fa-chevron-left"></i> Android 更好用的图片加载库
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/snowzhao/images/photo.png" alt="snowzhao">
            
              <p class="site-author-name" itemprop="name">snowzhao</p>
              <p class="site-description motion-element" itemprop="description">给自己每天浇点水,迟早会长成一棵大树</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/snowzhao/archives">
              
                  <span class="site-state-item-count">11</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/snowzhao/categories/index.html">
                  <span class="site-state-item-count">4</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/snowzhao/tags/index.html">
                  <span class="site-state-item-count">4</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/zhaoyingtao" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://blog.csdn.net/qq_31796651" target="_blank" title="CSDN">
                      
                        <i class="fa fa-fw fa-stack-overflow"></i>CSDN</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">snowzhao</span>

<!-- 取消英文统计数字
  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">7.4k</span>
  
-->
</div>
<!-- 取消默认 由 hexo 强力驱动 | 主题 next。pisces v5.1.4

  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>



-->



<span class="post-meta-divider"> 坚持 </span>

<span class="post-meta-divider"> | </span>

<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共 7.4k 字</span>
</div>

        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/snowzhao/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/snowzhao/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/snowzhao/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/snowzhao/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/snowzhao/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/snowzhao/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/snowzhao/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/snowzhao/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/snowzhao/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/snowzhao/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/snowzhao/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/snowzhao/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/snowzhao/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

<script src="/snowzhao/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"jsonPath":"/snowzhao/live2dw/assets/assets/z16.model.json"},"display":{"position":"right","width":300,"height":500},"mobile":{"show":false},"log":false});</script></body>
</html>
